package org.groupg.project.configmanager.util;



import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 剪贴板工具类
 * 提供复制文本到剪贴板的功能，以及创建带复制功能的UI组件
 */
public class ClipboardUtil {

    /**
     * 复制文本到剪贴板
     * @param text 要复制的文本
     */
    public static void copyToClipboard(String text) {
        try {
            StringSelection stringSelection = new StringSelection(text);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                "复制到剪贴板失败: " + e.getMessage(),
                "复制错误",
                JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 复制文本到剪贴板并显示成功消息
     * @param text 要复制的文本
     * @param parentComponent 父组件，用于显示消息对话框
     */
    public static void copyToClipboardWithMessage(String text, Component parentComponent) {
        copyToClipboard(text);
        JOptionPane.showMessageDialog(parentComponent,
            "已复制到剪贴板: " + (text.length() > 50 ? text.substring(0, 50) + "..." : text),
            "复制成功",
            JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 创建带复制按钮的标签面板
     * @param labelText 标签文本
     * @param value 要显示和复制的值
     * @return 包含标签、值和复制按钮的面板
     */
    public static JPanel createCopyableLabelPanel(String labelText, String value) {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        JLabel valueLabel = new JLabel(value != null ? value : "");
        JButton copyButton = new JButton("复制");

        // 设置复制按钮样式
        copyButton.setMargin(new Insets(2, 5, 2, 5));
        copyButton.setFocusPainted(false);

        copyButton.addActionListener(e -> {
            copyToClipboard(value != null ? value : "");
            JOptionPane.showMessageDialog(panel,
                "已复制到剪贴板: " + (value != null && value.length() > 50 ? value.substring(0, 50) + "..." : value),
                "复制成功",
                JOptionPane.INFORMATION_MESSAGE);
        });

        panel.add(new JLabel(labelText), BorderLayout.WEST);
        panel.add(valueLabel, BorderLayout.CENTER);
        panel.add(copyButton, BorderLayout.EAST);

        return panel;
    }

    /**
     * 创建带复制按钮的文本区域面板
     * @param labelText 标签文本
     * @param value 要显示和复制的值
     * @return 包含标签、文本区域和复制按钮的面板
     */
    public static JPanel createCopyableTextAreaPanel(String labelText, String value) {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        JTextArea textArea = new JTextArea(value != null ? value : "");
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBackground(UIManager.getColor("Panel.background"));

        JButton copyButton = new JButton("复制");
        copyButton.setMargin(new Insets(2, 5, 2, 5));
        copyButton.setFocusPainted(false);

        copyButton.addActionListener(e -> {
            copyToClipboard(textArea.getText());
            JOptionPane.showMessageDialog(panel, "已复制到剪贴板", "复制成功", JOptionPane.INFORMATION_MESSAGE);
        });

        panel.add(new JLabel(labelText), BorderLayout.NORTH);
        panel.add(new JScrollPane(textArea), BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(copyButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建带复制按钮的文本字段面板
     * @param labelText 标签文本
     * @param textField 文本字段组件
     * @return 包含标签、文本字段和复制按钮的面板
     */
    public static JPanel createCopyableTextFieldPanel(String labelText, JTextField textField) {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        JButton copyButton = new JButton("复制");
        copyButton.setMargin(new Insets(2, 5, 2, 5));
        copyButton.setFocusPainted(false);

        copyButton.addActionListener(e -> {
            copyToClipboard(textField.getText());
            JOptionPane.showMessageDialog(panel,
                "已复制到剪贴板: " + textField.getText(),
                "复制成功",
                JOptionPane.INFORMATION_MESSAGE);
        });

        panel.add(new JLabel(labelText), BorderLayout.WEST);
        panel.add(textField, BorderLayout.CENTER);
        panel.add(copyButton, BorderLayout.EAST);

        return panel;
    }

    /**
     * 为文本组件添加上下文菜单（右键菜单）
     * @param textComponent 文本组件（JTextField, JTextArea等）
     */
    public static void addCopyContextMenu(JTextComponent textComponent) {
        JPopupMenu contextMenu = new JPopupMenu();
        JMenuItem copyItem = new JMenuItem("复制");
        JMenuItem selectAllItem = new JMenuItem("全选");

        copyItem.addActionListener(e -> {
            textComponent.copy();
            JOptionPane.showMessageDialog(textComponent, "已复制选中内容", "复制成功", JOptionPane.INFORMATION_MESSAGE);
        });

        selectAllItem.addActionListener(e -> textComponent.selectAll());

        contextMenu.add(copyItem);
        contextMenu.add(selectAllItem);

        textComponent.setComponentPopupMenu(contextMenu);
    }

    /**
     * 为表格添加上下文菜单
     * @param table 表格组件
     * @param tableModel 表格模型
     */
    public static void addTableContextMenu(JTable table, javax.swing.table.TableModel tableModel) {
        JPopupMenu tableMenu = new JPopupMenu();
        JMenuItem copyCellItem = new JMenuItem("复制单元格");
        JMenuItem copyRowItem = new JMenuItem("复制整行");
        JMenuItem copyAllItem = new JMenuItem("复制所有数据");

        copyCellItem.addActionListener(e -> copySelectedTableCell(table, tableModel));
        copyRowItem.addActionListener(e -> copySelectedTableRow(table, tableModel));
        copyAllItem.addActionListener(e -> copyAllTableData(table, tableModel));

        tableMenu.add(copyCellItem);
        tableMenu.add(copyRowItem);
        tableMenu.add(copyAllItem);

        table.setComponentPopupMenu(tableMenu);
    }

    /**
     * 复制选中的表格单元格
     */
    private static void copySelectedTableCell(JTable table, javax.swing.table.TableModel tableModel) {
        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        if (row >= 0 && col >= 0) {
            Object value = tableModel.getValueAt(row, col);
            if (value != null) {
                copyToClipboard(value.toString());
                JOptionPane.showMessageDialog(table,
                    "已复制: " + value,
                    "复制成功",
                    JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(table,
                "请先选择一个单元格",
                "提示",
                JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 复制选中的表格行
     */
    private static void copySelectedTableRow(JTable table, javax.swing.table.TableModel tableModel) {
        int row = table.getSelectedRow();
        if (row >= 0) {
            StringBuilder rowData = new StringBuilder();
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Object value = tableModel.getValueAt(row, col);
                rowData.append(tableModel.getColumnName(col)).append(": ").append(value);
                if (col < tableModel.getColumnCount() - 1) {
                    rowData.append(" | ");
                }
            }
            copyToClipboard(rowData.toString());
            JOptionPane.showMessageDialog(table,
                "已复制整行数据",
                "复制成功",
                JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(table,
                "请先选择一行",
                "提示",
                JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 复制所有表格数据
     */
    private static void copyAllTableData(JTable table, javax.swing.table.TableModel tableModel) {
        StringBuilder allData = new StringBuilder();

        // 添加表头
        for (int col = 0; col < tableModel.getColumnCount(); col++) {
            allData.append(tableModel.getColumnName(col));
            if (col < tableModel.getColumnCount() - 1) {
                allData.append("\t");
            }
        }
        allData.append("\n");

        // 添加数据行
        for (int row = 0; row < tableModel.getRowCount(); row++) {
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Object value = tableModel.getValueAt(row, col);
                allData.append(value != null ? value.toString() : "");
                if (col < tableModel.getColumnCount() - 1) {
                    allData.append("\t");
                }
            }
            allData.append("\n");
        }

        copyToClipboard(allData.toString());
        JOptionPane.showMessageDialog(table,
            "已复制所有数据 (" + tableModel.getRowCount() + " 行)",
            "复制成功",
            JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 创建带复制功能的只读文本字段
     * @param text 初始文本
     * @return 配置好的只读文本字段
     */
    public static JTextField createCopyableTextField(String text) {
        JTextField textField = new JTextField(text);
        textField.setEditable(false);
        textField.setBackground(UIManager.getColor("Panel.background"));
        addCopyContextMenu(textField);
        return textField;
    }

    /**
     * 创建带复制功能的只读文本区域
     * @param text 初始文本
     * @param rows 行数
     * @param columns 列数
     * @return 配置好的只读文本区域
     */
    public static JTextArea createCopyableTextArea(String text, int rows, int columns) {
        JTextArea textArea = new JTextArea(text, rows, columns);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBackground(UIManager.getColor("Panel.background"));
        addCopyContextMenu(textArea);
        return textArea;
    }

    /**
     * 为组件添加简单的复制功能（点击按钮复制指定文本）
     * @param component 要添加复制按钮的组件
     * @param textToCopy 要复制的文本
     * @param buttonText 按钮文本（默认为"复制"）
     * @return 包含组件和复制按钮的面板
     */
    public static JPanel wrapWithCopyButton(JComponent component, String textToCopy, String buttonText) {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        JButton copyButton = new JButton(buttonText != null ? buttonText : "复制");
        copyButton.setMargin(new Insets(2, 5, 2, 5));
        copyButton.setFocusPainted(false);

        copyButton.addActionListener(e -> {
            copyToClipboard(textToCopy);
            JOptionPane.showMessageDialog(panel,
                "已复制到剪贴板",
                "复制成功",
                JOptionPane.INFORMATION_MESSAGE);
        });

        panel.add(component, BorderLayout.CENTER);
        panel.add(copyButton, BorderLayout.EAST);

        return panel;
    }
}